<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion">后台管理</i>
      </el-breadcrumb-item>
      <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <template>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" align="center" width="50"></el-table-column>
        <el-table-column prop="avatar" label="头像" align="center" width="80">
          <template slot-scope="scope">
            <el-avatar :size="50" :src="scope.row.avatar"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" align="center" width="100" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="phone" label="手机号码" align="center" width="110"></el-table-column>
        <el-table-column prop="email" label="电子邮箱" align="center" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="description" header-align="center" label="简介"></el-table-column>
        <el-table-column prop="enable" label="是否启用" align="center" width="80">
          <template slot-scope="scope">
            <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="openEditDialog(scope.row)" circle icon="el-icon-edit"></el-button>
            <el-button size="mini" type="danger" @click="openDeleteConfirm(scope.row)" circle icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-dialog title="修改管理员" :visible.sync="dialogFormVisible">
      <el-form :model="editForm">
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-input v-model="editForm.avatar" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" :label-width="formLabelWidth">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      avatar: "",
      tableData: [],
      dialogFormVisible: false,
      editForm: {
        id: "",
        avatar: "",
        nickname: "",
        phone: "",
        email: "",
        description: "",
        enable: "",
      },
      formLabelWidth: "120px",
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    loadAdminList() {
      // console.log("local storage jwt = " + jwt);
      let url = "http://localhost:9088/admins";
      console.log("url = " + url);

      // 使用axios携带jwt发起请求
      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .get(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.tableData = responseBody.data;
          }
        });
    },
    openEditDialog(admin) {
      let url = "http://localhost:9088/admins/" + admin.id;
      console.log("url = " + url);

      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .get(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.editForm = responseBody.data;
            this.dialogFormVisible = true;
          } else {
            this.$alert(responseBody.message, "操作失败", {
              confirmButtonText: "确定",
              callback: (action) => {
                this.loadAdminList();
              },
            });
          }
        });
    },
    submitEdit() {
      let url = "http://localhost:9088/admins/" + this.editForm.id + "/update";
      console.log("url = " + url);
      let formData = this.qs.stringify(this.editForm);
      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .post(url, formData)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.$message({
              message: "修改管理员信息成功！",
              type: "success",
            });
            this.loadAdminList();
          } else if (responseBody.state == 40400) {
            this.$alert(responseBody.message, "警告", {
              confirmButtonText: "确定",
              callback: (action) => {
                this.dialogFormVisible = false;
                this.loadAdminList();
              },
            });
          } else {
            this.$message.error(responseBody.message);
          }
        });
    },
    openDeleteConfirm(admin) {
      this.$confirm("此操作将永久删除【" + admin.nickname + "】, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.handleDelete(admin);
        })
        .catch(() => {});
    },
    toggleEnable(admin) {
      let enableText = ["禁用", "启用"];
      let url = "http://localhost:9088/admins/" + admin.id;
      if (admin.enable == 1) {
        url += "/enable";
      } else {
        url += "/disable";
      }
      console.log("url = " + url);
      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .post(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            let message = "操作成功，已经将【" + admin.nickname + "】状态更改为【" + enableText[admin.enable] + "】！";
            this.$message({
              message: message,
              type: "success",
            });
          } else {
            this.$message.error(responseBody.message);
            this.loadCategoryList();
          }
        });
    },
    handleDelete(admin) {
      let url = "http://localhost:9088/admins/" + admin.id + "/delete";
      console.log("url = " + url);

      this.axios
        .create({
          headers: {
            Authorization: localStorage.getItem("jwt"),
          },
        })
        .post(url)
        .then((response) => {
          let responseBody = response.data;
          if (responseBody.state == 20000) {
            this.$message({
              message: "删除成功！",
              type: "success",
            });
            this.loadAdminList();
          } else if (responseBody.state == 40400) {
            this.$alert(responseBody.message, "警告", {
              confirmButtonText: "确定",
              callback: (action) => {
                this.loadAdminList();
              },
            });
          } else {
            this.$message.error(responseBody.message);
          }
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {},
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
    this.loadAdminList();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
